<template>
  <a-form ref="form" :model="formData" layout="vertical">
    <div class="form__box">
      <a-form-item :label="`数据绑定key`" field="dataIndex">
        <template v-if="dataObj.mode === 'dataView'">
          <a-select
            v-model="formData.dataViewSel"
            allow-clear
            @change="changeDataViewSel"
          >
            <a-option value="手填">手填</a-option>
            <a-option
              v-for="option in dataObj.queryGroupList"
              :key="option.groupId + ' ' + option.queryKey"
              :value="option.groupId + ' ' + option.queryKey"
              :disabled="
                dataObj.pageData.some(
                  (item) =>
                    item.formData.dataIndex ===
                    option.groupId + ' ' + option.queryKey
                )
              "
              :title="
                (option.formName
                  ? `${option.formName}_${option.columnName}`
                  : option.columnName) +
                (option.aggregateId
                  ? `（${option.funColumnAs}的函数条件）`
                  : '')
              "
              >{{
                option.formName
                  ? `${option.formName}_${option.columnName}`
                  : option.columnName
              }}{{
                option.aggregateId ? `（${option.funColumnAs}函数条件）` : ""
              }}</a-option
            >
          </a-select>
          <a-input
            v-model="formData.dataIndex"
            :disabled="formData.dataViewSel !== '手填'"
          ></a-input>
        </template>
        <a-input
          v-else
          v-model="formData.dataIndex"
          :disabled="formData.notMod"
        ></a-input>
        <field-linkage
          :formData="formData"
          :dataShowFieldOptions="dataShowFieldOptions"
        ></field-linkage>
      </a-form-item>
      <a-form-item label="将值赋给下列字段" v-if="dataObj.mode === 'dataView'">
        <a-select
          v-model="formData.assignmentList"
          multiple
          allow-clear
          @change="changeAssignmentList"
        >
          <a-option
            v-for="option in dataObj.queryGroupList"
            :key="option.groupId + ' ' + option.queryKey"
            :value="option.groupId + ' ' + option.queryKey"
            >{{
              option.formName
                ? `${option.formName}_${option.columnName}`
                : option.columnName
            }}{{
              option.aggregateId ? `（${option.funColumnAs}函数条件）` : ""
            }}</a-option
          >
        </a-select>
      </a-form-item>
      <a-form-item :label="`字段名称`" field="name">
        <a-input v-model="formData.name"></a-input>
        <a-checkbox v-model="formData.hideTitle">隐藏标题</a-checkbox>
      </a-form-item>
      <a-form-item :label="`控件类型`" field="type">
        <a-select
          v-model="formData.type"
          @change="changeControlTypes($event, formData)"
        >
          <a-option
            :value="item.value"
            v-for="item in typeOptions"
            :key="item.value"
          >
            {{ item.label }}
          </a-option>
        </a-select>
      </a-form-item>
      <a-form-item :label="`数据类型`" field="dataType">
        <a-select v-model="formData.dataType" @change="dataTypeChange">
          <a-option
            :value="item.value"
            v-for="item in dataTypeOptions"
            :key="item.value"
          >
            {{ item.label }}
          </a-option>
        </a-select>
      </a-form-item>
      <a-form-item
        :label="`日期类型`"
        field="typeFormat"
        v-if="formData.dataType === 'timestamp'"
      >
        <a-select v-model="formData.typeFormat">
          <a-option value="YYYY">年</a-option>
          <a-option value="YYYY-MM">年/月</a-option>
          <a-option value="YYYY-MM-DD">年/月/日</a-option>
          <a-option value="YYYY-MM-DD HH:mm:ss">年/月/日 时分秒</a-option>
        </a-select>
      </a-form-item>
      <a-form-item :label="`内容提示`" field="placeholder">
        <a-input v-model="formData.placeholder"></a-input>
      </a-form-item>
      <a-form-item :label="`表单栅格`" field="wrapperCol">
        <a-input-number
          :step="1"
          :max="24"
          :min="6"
          v-model="formData.wrapperCol"
        ></a-input-number>
      </a-form-item>

      <a-tabs v-model="formData.dataSource">
        <a-tab-pane key="" title="静态数据">
          <a-form-item :label="`数据内容`">
            <div class="opts_chunk">
              <a-radio-group v-model="formData.defaultValue">
                <draggable :list="formData.opts" item-key="key">
                  <template #item="{ element }">
                    <a-radio
                      style="width: 100%"
                      :key="`${element.key}`"
                      :value="`${element.value}`"
                    >
                      {{ element.value }}
                      <icon-delete
                        class="del_icon"
                        @click="delOption(element.key)"
                      />
                    </a-radio>
                  </template>
                </draggable>
              </a-radio-group>
            </div>
            <div style="width: 98%; display: flex">
              <a-input
                v-model="formData.selectText"
                style="margin-left: 5px; margin-right: 5px"
                placeholder="请输入选项"
              >
              </a-input>
              <a-button @click="addOption">添加</a-button>
            </div>
          </a-form-item>
        </a-tab-pane>
        <!--        <a-tab-pane key="foreign" title="外键查表">-->
        <!--          <a-form-item label="查询键名">-->
        <!--            <a-select multiple v-model="formData.dataOptionField">-->
        <!--              <a-option v-for="item in nameList" :key="item.value" :value="item.value">{{ item.label }}</a-option>-->
        <!--            </a-select>-->
        <!--            &lt;!&ndash;            <linked-form-query :formData="formData"></linked-form-query>&ndash;&gt;-->
        <!--          </a-form-item>-->
        <!--        </a-tab-pane>-->
        <a-tab-pane key="dataSource" title="数据源">
          <a-form-item label="查询数据源">
            <a-select
              v-model="formData.dataSourceId"
              @change="queryDataSourceDetails($event)"
              :filter-option="false"
              @search="queryDatasourceList"
              show-search
              allow-clear
            >
              <a-option
                v-for="item in dataSourceList"
                :key="item.dataId"
                :value="item.dataId"
                :title="item.dataName"
              >
                {{ item.dataName }}
              </a-option>
            </a-select>
            <!-- <linked-form-query :formData="formData"></linked-form-query>-->
          </a-form-item>
          <a-form-item label="展示字段">
            <a-select v-model="formData.dataShowFields" multiple allow-clear>
              <a-option
                v-for="item in dataShowFieldOptions"
                :key="item.columnAs"
                :value="item.columnAs"
              >
                {{ item.columnAs }}
              </a-option>
            </a-select>
          </a-form-item>
          <a-form-item label="展示字段排序">
            <draggable tag="div" :list="formData.dataShowFields">
              <template #item="{ element }">
                <li :key="element">
                  <icon-drag-dot-vertical /> {{ element }}
                </li>
              </template>
            </draggable>
          </a-form-item>
          <a-form-item label="传值字段">
            <a-select v-model="formData.dataOptionField" allow-clear>
              <a-option
                v-for="item in dataShowFieldOptions"
                :key="item.columnAs"
                :value="item.columnAs"
              >
                {{ item.columnAs }}
              </a-option>
            </a-select>
          </a-form-item>
          <a-tabs>
            <a-tab-pane
              v-for="(groupItem, index) in formData.dataCondition"
              :title="`条件组${index + 1}`"
              :key="
                groupItem.tableQueryMappingAddDTO?.groupId || groupItem.groupId
              "
            >
              <a-form-item
                v-for="item in groupItem.tableQueryGroupAddDTOList"
                :key="item.groupId + item.columnKey"
                :label="`条件字段：${item.columnKey}`"
              >
                <template v-if="!item.between">
                  <a-select
                    v-model="item.dataIndex"
                    allow-clear
                    placeholder="请选择映射字段"
                  >
                    <a-option
                      v-for="option in nameList"
                      :key="option.dataIndex"
                      :value="option.dataIndex"
                      :disabled="
                        formData.dataCondition.some(
                          (e) => e.dataIndex === option.dataIndex
                        )
                      "
                      >{{ option.name }}</a-option
                    >
                  </a-select>
                  <a-input
                    v-model="item.defaultTheValue"
                    placeholder="条件默认传参"
                  ></a-input>
                </template>
                <template v-else>
                  <span
                    v-for="(betweenItem, betweenIndex) in item.between"
                    :key="betweenItem.queryKey"
                  >
                    <a-select
                      v-model="betweenItem.dataIndex"
                      allow-clear
                      :placeholder="`请选择 条件${betweenIndex + 1} 映射字段`"
                    >
                      <a-option
                        v-for="option in nameList"
                        :key="option.dataIndex"
                        :value="option.dataIndex"
                        :disabled="
                          formData.dataCondition.some(
                            (e) => e.dataIndex === option.dataIndex
                          )
                        "
                        >{{ option.name }}</a-option
                      >
                    </a-select>
                    <a-input
                      v-model="betweenItem.defaultTheValue"
                      :placeholder="`条件${betweenIndex + 1}默认传参`"
                    ></a-input>
                  </span>
                </template>
              </a-form-item>
            </a-tab-pane>
          </a-tabs>
          <a-form-item label="是否忽略权限">
            <a-switch v-model="formData.readUnlimited" />
          </a-form-item>
        </a-tab-pane>
        <a-tab-pane key="data" title="配置接口">
          <template v-if="formData.request">
            <a-form-item label="数据链接">
              <a-input
                v-model="formData.request.url"
                placeholder="请输入数据链接"
              ></a-input>
            </a-form-item>
            <a-form-item label="请求方式">
              <a-select v-model="formData.request.method">
                <a-option value="post">POST</a-option>
                <a-option value="get">GET</a-option>
              </a-select>
            </a-form-item>
            <a-form-item label="发送参数">
              <a-input
                v-model="formData.request.params"
                placeholder="请输入发送参数（JSON格式）"
              ></a-input>
            </a-form-item>
            <a-form-item label="接收参数选项">
              <a-input
                v-model="formData.request.returnValue"
                placeholder="请输入接收数据结构"
              ></a-input>
              <a-input
                v-model="formData.request.key"
                placeholder="请输入接收label(展示字段)"
              ></a-input>
              <a-input
                v-model="formData.request.value"
                placeholder="请输入接收value(接收字段)"
              ></a-input>
            </a-form-item>
          </template>
        </a-tab-pane>
      </a-tabs>
      <a-form-item :label="`配置属性`" field="defaultValue">
        <a-checkbox v-model="formData.isMultiple" @change="isMultipleChange"
          >可多选</a-checkbox
        >
        <a-checkbox v-model="formData.isSearch">可搜索</a-checkbox>
        <a-checkbox v-model="formData.checkedFirstOption"
          >新增勾选第一项</a-checkbox
        >
      </a-form-item>
      <a-form-item :label="`默认值`" field="defaultValue">
        <a-input v-model="formData.defaultValue"></a-input>
      </a-form-item>
      <a-form-item :label="`展示属性`" field="listStyleShow">
        <a-select v-model="formData.listStyleShow">
          <a-option value="text">文字展示</a-option>
          <a-option value="tag">标签展示</a-option>
        </a-select>
      </a-form-item>
      <a-form-item
        :label="`标签颜色`"
        v-if="formData.listStyleShow === 'tag'"
        field="tagColor"
      >
        <a-select v-model="formData.tagColor">
          <a-option
            :value="item.value"
            v-for="item in tagColorList"
            :key="item.value"
          >
            {{ item.label }}
          </a-option>
        </a-select>
      </a-form-item>
      <!--      <a-form-item :label="`默认值`" :field="`defaultValue`">-->
      <!--        <a-input v-model="formData.defaultValue"></a-input>-->
      <!--      </a-form-item>-->
      <a-form-item :label="`操作属性`" field="defaultValue">
        <a-checkbox v-model="formData.hide">隐藏</a-checkbox>
        <a-checkbox v-model="formData.disabled">禁用</a-checkbox>
        <a-checkbox v-model="formData.desensitization">脱敏</a-checkbox>
        <!--        <a-checkbox :default-checked="true" v-model="formData.columnQuery">查询可见</a-checkbox>-->
      </a-form-item>
      <a-form-item :label="`校验`" field="required">
        <a-checkbox v-model="formData.required">必填</a-checkbox>
        <validate-key
          v-if="formData.required"
          :form-data="formData"
        ></validate-key>
      </a-form-item>
      <a-form-item :label="`字段说明`" field="explain">
        <a-textarea v-model="formData.explain">必填</a-textarea>
      </a-form-item>
    </div>
  </a-form>
</template>
<script>
import { nanoid } from "nanoid";
import {
  basicDefaultData,
  tagColorList,
  typeOptions,
} from "@/components/Form/base/options";
import FieldLinkage from "@/components/Form/base/fieldLinkage.vue";
import LinkedFormQuery from "@/components/Form/base/LinkedFormQuery.vue";
import _ from "lodash";
import ValidateKey from "@/components/Form/base/validateKey.vue";
import {
  changeAssignmentList,
  changeControlTypes,
  changeDataViewSel,
} from "@/mixins/methodsMixins";

export const defaultData = () => ({
  ...basicDefaultData(),
  name: "下拉框选择",
  placeholder: "",
  type: "select",
  opts: [],
  defaultValue: "",
  wrapperCol: 24,
  dataSource: "",
  allowClear: false, // 支持清除
  isMultiple: false, // 是否可多选
  isSearch: false, // 是否可搜索
  dataSourceId: "", // 数据源ID
  dataOptionField: "", // 数据源传值字段
  dataCondition: [], // 数据源与当前表字段绑定关系
  dataShowFields: [], // 数据源展示字段
  linkedFormQuery: {},
  typeFormat: "", // 日期格式
  checkedFirstOption: false,
  request: {
    url: "",
    method: "post",
    key: "",
    value: "",
    params: "",
    returnValue: "", // 返回数据结构
  }, // 请求opts数据链接
});
export const dataTypeOptions = [
  {
    label: "string",
    value: "string",
  },
  {
    label: "long",
    value: "long",
  },
  {
    label: "int",
    value: "int",
  },
  {
    label: "float",
    value: "float",
  },
  {
    label: "double",
    value: "double",
  },
  {
    label: "list",
    value: "list",
  },
  {
    label: "timestamp",
    value: "timestamp",
  },
];
export default {
  name: "SelectInfo",
  components: { ValidateKey, LinkedFormQuery, FieldLinkage },
  inject: ["dataObj"],
  data() {
    return {
      rules: {
        name: [{ required: true, message: "必填" }],
      },
      dataSourceList: [], // 数据源列表
      dataShowFieldOptions: [], // 数据源展示字段
      dataTypeOptions,
      tagColorList,
      typeOptions,
    };
  },
  computed: {
    formData() {
      return this.dataObj.pageData[this.dataObj.selectIndex]?.formData || {};
    },
    nameList() {
      return [{ name: "_id", dataIndex: "_id" }].concat(
        this.dataObj.pageData
          .filter((item) => item.formData.dataIndex && item.formData.name)
          .map((item) => {
            return {
              name: item.formData.name,
              dataIndex: item.formData.dataIndex,
            };
          })
      );
    },
  },
  watch: {
    formData: {
      immediate: true,
      handler(newVal) {
        console.log(newVal);
        if (newVal.name === undefined) {
          this.dataObj.pageData[this.dataObj.selectIndex].formData =
            defaultData();
          console.log(
            "select",
            this.dataObj.pageData[this.dataObj.selectIndex].formData
          );
        }
      },
    },
  },
  methods: {
    changeAssignmentList,
    changeDataViewSel,
    changeControlTypes,
    // 选择了数据源，需要查询有哪些展示字段
    async queryDataSourceDetails(dataId, id, dataShowFields) {
      try {
        if (!dataId) {
          this.formData.dataCondition = [];
          return;
        }
        this.formData.dataOptionField = id || null;
        this.formData.dataShowFields = dataShowFields || [];
        const result = await this.$http.get(
          "/datasource/queryDataSourceDetail",
          {
            params: {
              dataId,
            },
          }
        );
        const { data } = result;
        const { dataColumnQueryDTOList, aggregateFunctionInfoReqDTO } = data;
        const { aggregateFunctionInfoAddDTOList } =
          aggregateFunctionInfoReqDTO || {};
        const mergedList = dataColumnQueryDTOList.concat(
          aggregateFunctionInfoAddDTOList || []
        );
        // 需要根据columnKey去重后的对象数组，而不是单纯的columnKey集合，可以进一步处理：
        this.dataShowFieldOptions = mergedList.filter((item, index, self) => {
          return index === self.findIndex((t) => t.columnAs === item.columnAs);
        });
        _.assign(this.formData, {
          dataCondition: data.queryGroupReqDTOList?.map((item) => {
            let oldData = {};
            if (id) {
              // 编辑时，先查找原先的值,旧模式
              oldData = this.formData.dataCondition?.find(
                (e) =>
                  e.groupId === item.tableQueryMappingAddDTO.groupId &&
                  e.columnKey === item.tableQueryMappingAddDTO.columnKey
              );
            }
            item.tableQueryGroupAddDTOList.forEach((queryItem) => {
              if (!_.isEmpty(oldData) && !queryItem.between) {
                queryItem.dataIndex = oldData?.dataIndex || null;
                queryItem.defaultTheValue = oldData?.defaultTheValue || null;
              } else {
                const oldV2Data = this.findMatchingQuery(
                  this.formData.dataCondition,
                  queryItem.groupId,
                  queryItem.queryKey
                );
                if (
                  _.isArray(queryItem.between) &&
                  queryItem.between.length &&
                  oldV2Data?.between
                ) {
                  queryItem.between[0] = oldV2Data?.between?.[0];
                  queryItem.between[1] = oldV2Data?.between?.[1];
                } else if (!_.isArray(queryItem.between)) {
                  queryItem.defaultTheValue =
                    oldV2Data?.defaultTheValue || null;
                  queryItem.dataIndex = oldV2Data?.dataIndex || null;
                }
              }
            });

            return _.cloneDeep(item);
          }),
        });
        console.log(this.formData.dataCondition, "输出");
      } catch (e) {
        console.error("请求失败", e);
      }
    },
    findMatchingQuery(dataCondition = [], groupId, queryKey) {
      for (const condition of dataCondition) {
        const group = condition.tableQueryGroupAddDTOList;
        if (group) {
          for (const item of group) {
            // 查找具有指定 groupId 和 queryKey 的对象
            if (item.groupId === groupId && item.queryKey === queryKey) {
              return item;
            }
          }
        }
      }

      return null; // 如果没有找到匹配项，则返回 null
    },
    // 查询数据源列表
    async queryDatasourceList(dataName) {
      // try {
      //   const result = await this.$http.post(`/datasource/querySourceAllList`, {
      //     dataTypeList: ["select", "selTable", "interface"],
      //     dataName: dataName || "",
      //   });
      //   const { data } = result;
      //   this.dataSourceList = data;
      // } catch (e) {
      //   console.error("请求失败", e);
      // }
    },
    showModal() {
      this.$refs.linkedFormQuery.open();
    },
    dataTypeChange(e) {
      if (e === "timestamp") {
        this.formData.typeFormat = "YYYY-MM-DD";
      }
      this.formData.required = e === "list";
    },
    // 可多选时数据类型改变
    isMultipleChange(e) {
      if (e.target.checked) {
        this.formData.dataType = "list";
        // this.formData.required = true
      } else {
        this.formData.dataType = "string";
        // this.formData.required = false
      }
    },
    addOption() {
      if (this.formData.selectText) {
        if (!this.formData.opts) {
          this.formData.opts = [];
        }
        this.formData.opts.push({
          key: nanoid(),
          value: this.formData.selectText,
        });
        this.formData.selectText = "";
      }
    },
    delOption(key) {
      const index = this.formData.opts.findIndex((item) => item.key === key);
      console.log(key, index);
      // 判断若是默认值则删除默认值
      if (this.formData.defaultValue === this.formData.opts[index].value) {
        this.formData.defaultValue = "";
      }
      this.formData.opts.splice(index, 1);
    },
  },
  created() {
    this.queryDatasourceList(); // 查询数据源列表
    const { dataSourceId, dataOptionField } = this.formData;
    const dataShowFields = this.formData.dataShowFields;
    if (dataSourceId) {
      this.queryDataSourceDetails(
        dataSourceId,
        dataOptionField,
        dataShowFields
      );
    }
  },
};
</script>

<style scoped lang="less">
.opts_chunk {
  width: 100%;
  margin-top: 5px;
  margin-bottom: 5px;

  /deep/ .arco-radio-group {
    width: 100%;
  }

  .del_icon {
    // color: red;
    font-size: 16px;
    position: absolute;
    right: 10px;
    cursor: pointer;
  }

  .del_icon:hover {
    color: red;
  }
}
</style>
